const Router = require('koa-router')
const mongoose = require('mongoose')

let router = new Router()
router.get('/', async (ctx) => {
    ctx.body = "这是用户操作首页"
})

router.post('/register', async (ctx) => {

    //用try-catch来回调
    try {
        const User = mongoose.model('User')
        let newUser = new User(ctx.request.body)
        await newUser.save()
        ctx.body = { code: 200, message: '注册成功' }
    } catch (error) {
        ctx.body = { code: 500, message: error }

    }




    // const User = mongoose.model('User')
    // let newUser = new User(ctx.request.body)

    // await newUser.save().then(()=>{
    //     ctx.body={
    //         code:200,
    //         message:'注册成功'
    //     }
    // }).catch(error=>{
    //     ctx.body={
    //         code:500,
    //         message:error
    //     }
    // })
})

router.post('/login', async (ctx) => {
    let loginUser = ctx.request.body
    console.log(loginUser)
    let userName = loginUser.userName
    let password = loginUser.password

    //引入User的model
    const User = mongoose.model('User')
    await User.findOne({ userName: userName }).exec().then(async (result, userName) => {

        //result :    _id: 5cd2f7e1042a37330cf3c970,
        //   userName: 'jsxiong',
        //   password: '123456',
        //   __v: 0 }
        //改造下  因为加盐加密功能实现不了           


        if (result) {
            let newUser = new User()
            await newUser.comparePassword(password, result.password)
                .then(() => {
                    ctx.body = { code: 200, message: '注册成功啦' }
                })
                .catch(() => {
                    console.log(error)
                    ctx.body = { code: 500, message: '注册失败' }
                })
        } else {
            ctx.body = { code: 201, message: '用户名不存在' }
        }
    }).catch(error => {
        console.log(error)
        ctx.body = { code: 500, message: '没有找到用户名' }
    })


    // try{
    //     if(result){
    //         if()
    //     }

    // }

})

module.exports = router